package com.kuang.controller;

import com.kuang.pojo.Books;
import com.kuang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

  @Autowired
  @Qualifier("BookServiceImpl")
  private BookService bookService;


  /**
   * 点击跳转查询所有书籍
   * 然后返回给allbook.jsp
   * 返回值省略了后缀 在mvc中有
   * @param model model是用来携带数据的东西
   * @return
   */
  @RequestMapping("/allBook")
  public String list(Model model) {
    List<Books> list = bookService.queryAllBook();
    model.addAttribute("list", list);
    return "allBook";
  }

  @RequestMapping("/toAddBook")
  public String toAddpager(){
    return "addBook";
  }

  @RequestMapping("addBook")
  public String addBook(Books books){
    bookService.addBook(books);
    return "redirect:/book/allBook";
  }


  /**
   * 这里也可以和del方法一样去更改 使用doget方法
   *
   * @param model 携带数据
   * @param id 用于选定更改的值
   * @return
   */
  @RequestMapping("/toUpdateBook")
  public String toUpdateBook(Model model, int id) {
    Books books = bookService.queryBookById(id);
    System.out.println(books);
    model.addAttribute("book",books );
    return "updateBook";
  }

  @RequestMapping("/updateBook")
  public String updateBook(Model model, Books book) {
    System.out.println(book);
    bookService.updateBook(book);
    Books books = bookService.queryBookById(book.getBookID());
    model.addAttribute("books", books);
    return "redirect:/book/allBook";
  }
  @RequestMapping("/del/{bookId}")
  public String deleteBook(@PathVariable("bookId") int id) {
    bookService.deleteBookById(id);
    return "redirect:/book/allBook";
  }


  @RequestMapping("/queryBook")
  public String queryBook(String queryBookName , Model model){
    System.out.println("进入queryBook=》"+queryBookName);
    Books books = bookService.queryBookName(queryBookName);

    List<Books> list = new ArrayList<>();

    list.add(books);
    if (books==null){

      list = (bookService.queryAllBook());
      model.addAttribute("error","未查到");
    }
    model.addAttribute("list",list);
    return "allBook";
  }

}